package com.demo.config.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.demo.common.constant.JWTConstants;
import com.demo.common.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Set;

/*
    关闭后端服务器时清除 redis 中所有令牌 token
 */
@Component
@Slf4j
public class ShutDownListener implements ApplicationListener<ContextClosedEvent> {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        log.info("服务器已关闭，redis 令牌 token 正在清除……");
        // 从redis中获取所有的令牌 token
        Set<String> keys = redisTemplate.keys(JWTConstants.JWT_REDIS_KEY_PREFIX + "*");
        if (CollectionUtil.isNotEmpty(keys)){
            // 将所有令牌 token 从 redis 中清除
            redisTemplate.delete(keys);
        }
    }
}
